package dm.ast;

import test.envset.GlobalState;

import java.util.List;

/**
 * @author weihuixin
 * @date 2024/4/17
 * @Description
 */
public class DmJoinExpression extends DmASTNode{
    public DmJoinType jointype = null;//join的类型
    public List<DmSingleJoinExpression> joinbool = null;
    public List<DmBoolOperator> ops = null;//操作符列表
    public DmColumn using = null;//using连接的列
    public int rightOrleft = 0;//表示左外或者右外连接
    public int tableIndex = 0;//记录join两边表的位置

    public DmJoinExpression(){

    }


    @Override
    public void setWidt() {
        if(joinbool == null){
            wid_t = 1;
        }else {
            wid_t = 1;//ON关键字
            for (int i = 0; i < joinbool.size(); i++) {
                joinbool.get(i).setWidt();
                wid_t += joinbool.get(i).wid_t;
            }
        }
    }

    @Override
    public void setDept() {
        if(joinbool == null){
            dep_t = 0;
        }else {
            dep_t = 1;
        }
    }

    @Override
    public DmDataType getExpressionType() {
        return null;
    }

    @Override
    public String toSql(){
        if(joinbool == null){
            return " ";
        }else {
            StringBuilder sql = new StringBuilder();
            sql.append(joinbool.get(0).toSql());
            for (int i = 1; i < joinbool.size(); i++) {
                sql.append(ops.get(i-1).toSql());
                sql.append(joinbool.get(i).toSql());
            }
            return String.format(" ON /*wid:%d*/ %s",joinbool.size()*3+ops.size(),sql.toString());
        }
    }

    @Override
    public void fill(GlobalState globalState) {
        if(!isCompleted){
            for (int i = 0; i < joinbool.size(); i++) {
                joinbool.get(i).filljoinsingle(globalState.getSelSource(tableIndex),globalState.getSelSource(tableIndex+1));
            }
            isCompleted = true;
        }
    }

    //处理sql错误
    public void fixErr4097(){
        for (int i = 0; i < joinbool.size(); i++) {
            DmExpression.fixErr4097Low(joinbool.get(i));
        }
    }
}
